package com.xxw.yygh.hosp.listener;

import com.rabbitmq.client.Channel;
import com.xxw.yygh.hosp.service.ScheduleService;
import com.xxw.yygh.mq.MqConst;
import com.xxw.yygh.mq.RabbitService;
import com.xxw.yygh.vo.msm.MsmVo;
import com.xxw.yygh.vo.order.OrderMqVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class OrderMqListener {

    @Resource
    private ScheduleService scheduleService;

    @Resource
    private RabbitService rabbitService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = MqConst.QUEUE_ORDER,durable = "true"),//创建队列
                    exchange = @Exchange(name = MqConst.EXCHANGE_DIRECT_ORDER),//创建交换机
                    key = MqConst.ROUTING_ORDER
            )
    })

    //确认挂号走该方法
    //取消预约也走该方法
    public void consume(OrderMqVo orderMqVo, Message message, Channel channel){
        String scheduleId = orderMqVo.getScheduleId();
        Integer availableNumber = orderMqVo.getAvailableNumber();
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (availableNumber != null) {
            //不为空表示为确认挂号操作
            //更新可预约数
            scheduleService.updateAvailableNumber(scheduleId, availableNumber);

        }else {
            //取消预约操作
            scheduleService.cancelSchedule(scheduleId);
        }

        if (msmVo != null) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS, MqConst.ROUTING_SMS_ITEM, msmVo);
        }

    }

}
